#!/usr/bin/python
# -*- coding:utf-8 -*-
#%%
import ctypes
import sys
import time
import cv2
import numpy as np
from array import array

#%%
ll = ctypes.cdll.LoadLibrary
lib = ll("/home/wang/Documents/share-memory/libc/build/linux/x86_64/release/libsharemem.so")

HEIGHT = 1080
WIDTH = 1920
MEMORY_SIZE = HEIGHT*WIDTH*3


share_mem_attach = False
buf=ctypes.create_string_buffer(MEMORY_SIZE)


def init_share_mem()->bool:
	global share_mem_attach
	if share_mem_attach == False:
		lib.init_share_mem.argtypes=[ctypes.c_int]
		ret_val=lib.init_share_mem(0)
		return False
	else:
		share_mem_attach = True
		return True


#%%
#desp		:	write string into share mem
#parms		:	write_string,the string you want write
#return		:	0 success, 1 error
def test_write_share_memory(write_string: str):
	init_share_mem()
	print(write_string)

	write_string_len=len(write_string)
	memsize=ctypes.c_int(write_string_len)


	#2. write string
	p_str =  bytes(write_string, "utf8")

	l = ctypes.c_int(write_string_len + 1)
	ret_val=lib.write_share_mem(p_str, l)
	if ret_val !=0:
		return 1




#%%
def test_read_share_memory():

	init_share_mem()

	#2. read bytes
	lib.read_share_mem.argtypes=[ctypes.c_char_p, ctypes.c_uint32]
	lib.read_share_mem.restype=ctypes.c_int
	global buf
	ret_val = lib.read_share_mem(buf, MEMORY_SIZE)
	if ret_val != 0:
		return -1
	
	return 0

#%%
def test_buf_to_img():
	global buf
	arr = np.frombuffer(buf, np.uint8)
	b = arr.reshape((HEIGHT, WIDTH, 3))
	
	img = cv2.cvtColor(b, cv2.COLOR_BGR2RGB)
	if img is not None:
		try:
			cv2.namedWindow("img", 0)
			cv2.imshow("img", img)
			key = cv2.waitKey(1) & 0xff
			if key == ord('q'):
				exit(0)
		except:
			pass
	
	

#%%
if __name__=='__main__':

	init_share_mem()
	while True:
		if test_read_share_memory() == 0:
			test_buf_to_img()
		# test_write_share_memory(write_string + str(i))
		# test_read_share_memory()
		# i = i + 1
		# time.sleep(0.01) # 10 ms

# %%
